package com.weds.edpf.core.web;


import com.alibaba.fastjson.JSONObject;
import com.weds.bean.jwt.JwtUtils;
import com.weds.core.annotation.Logs;
import com.weds.core.base.BaseCommPager;
import com.weds.core.base.BaseController;
import com.weds.core.base.BasePageSearch;
import com.weds.core.resp.JsonResult;
import com.weds.core.utils.ImageUtils;
import com.weds.core.utils.StringUtils;
import com.weds.edpf.core.entity.*;
import com.weds.edpf.core.service.*;
import com.weds.edpf.core.util.CharacterUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author sxm
 * @Description 部门管理
 * @Date 2018-12-13
 * @version
 * 新增部门，删除部门，修改部门  wangjianqiang 2020/06/12
 */
@RestController
@RequestMapping(value = "/dep")
@Api(value = "部门管理", description = "部门管理")
public class DepController extends BaseController {

    public static final String DEP_MODULE_ID = "0002";

    @Autowired
    private DepService depService;

    @Autowired
    private UserBaseService userBaseService;

    @Autowired
    private WtModuleService wtModuleService;

    @Autowired
    private DepDeleteService depDeleteService;

    @Autowired
    private UserLogService userLogService;

    @Resource
    private HttpServletRequest request;

    private Logger log = LogManager.getLogger();

    @Logs
    @ApiOperation(value = "新增Dep信息", notes = "新增Dep信息")
    @RequestMapping(value = "/insert", method = RequestMethod.PUT)
    public JsonResult<Object> insert(@RequestBody DepEntity record) {
        depService.insertSelective(record);
        return succMsg();
    }

    @Logs
    @ApiOperation(value = "更新Dep信息", notes = "更新Dep信息")
    @RequestMapping(value = "/updateByPrimaryKey", method = RequestMethod.POST)
    public JsonResult<Object> updateByPrimaryKey(@RequestBody DepEntity record) {
        depService.updateByPrimaryKeySelective(record);
        return succMsg();
    }

    @Logs
    @ApiOperation(value = "查询Dep清单", notes = "查询Dep清单")
    @RequestMapping(value = "/selectListPageByEntity", method = RequestMethod.POST)
    public JsonResult<BaseCommPager<DepEntity>> selectListPageByEntity(@RequestBody BasePageSearch<DepEntity> record) {
        setPageHelper(record);
        DepEntity entity = record.getSearch();
        if (entity == null) {
            entity = new DepEntity();
        }
        List<DepEntity> list = depService.selectListByEntity(entity);
        return succMsgData(new BaseCommPager<DepEntity>(list));
    }

    @Logs
    @ApiOperation(value = "查询Dep列表", notes = "查询Dep列表")
    @RequestMapping(value = "/selectListByEntity", method = RequestMethod.POST)
    public JsonResult<List<DepEntity>> selectListByEntity(@RequestBody DepEntity record) {
        List<DepEntity> list = depService.selectListByEntity(record);
        return succMsgData(list);
    }

    @Logs
    @ApiOperation(value = "删除Dep信息", notes = "删除Dep信息")
    @RequestMapping(value = "/deleteByPrimaryKey", method = RequestMethod.DELETE)
    public JsonResult<Object> deleteByPrimaryKey(@RequestParam Long depSerial) {
        depService.deleteByPrimaryKey(depSerial);
        return succMsg();
    }

    @Logs
    @ApiOperation(value = "查询Dep信息", notes = "查询Dep信息")
    @RequestMapping(value = "/selectByPrimaryKey", method = RequestMethod.GET)
    public JsonResult<DepEntity> selectByPrimaryKey(@RequestParam Long depSerial) {
        DepEntity entity = depService.selectByPrimaryKey(depSerial);
        return succMsgData(entity);
    }

    @Logs
    @ApiOperation(value = "查询Dep用户人数", notes = "查询Dep用户人数")
    @RequestMapping(value = "/selectDeptUserInfo", method = RequestMethod.GET)
    public JsonResult<DepUserEntity> selectDeptUserInfo(@RequestParam Integer depParentNo) {
        List<DepEntity> depList = depService.selectDeptUserNums(depParentNo);
        UserBaseEntity record = new UserBaseEntity();
        record.setUserDep(depParentNo);
        List<UserBaseEntity> userList = userBaseService.selectListByEntity(record);
        try {
            for (UserBaseEntity userBaseEntity : userList) {
                if (!StringUtils.isBlank(userBaseEntity.getHeadImage())) {
                    userBaseEntity.setHeadImage(ImageUtils.imgToBase64(userBaseEntity.getHeadImage()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        DepUserEntity depUserEntity = new DepUserEntity();
        depUserEntity.setDepList(depList);
        depUserEntity.setUserList(userList);
        return succMsgData(depUserEntity);
    }

    @Logs
    @ApiOperation(value = "查询机构树", notes = "查询机构树")
    @RequestMapping(value = "/selectOrgTree", method = RequestMethod.GET)
    public JsonResult<List<TreeNodeEntity>> selectOrgTree(@RequestParam Integer depParentNo) {
        List<DepEntity> depList = depService.selectOrgTree(depParentNo);
        TreeNodeEntity root = new TreeNodeEntity(depParentNo.toString());
        for (DepEntity depEntity : depList) {
            TreeNodeEntity treeNodeEntity = new TreeNodeEntity(depEntity.getDepSerial().toString(),
                    depEntity.getDepParent().toString(), depEntity.getDepName(), null, null);
            root.add(treeNodeEntity);
        }
        return succMsgData(root.getChildren());
    }

    @Logs
    @ApiOperation(value = "查询机构树异步", notes = "查询机构树异步")
    @RequestMapping(value = "/selectOrgTreeLazy", method = RequestMethod.GET)
    public JsonResult<List<TreeNodeEntity>> selectOrgTreeLazy(@RequestParam Integer depParentNo) {
        List<DepEntity> depList = depService.selectOrgTreeLazy(depParentNo);
        List<TreeNodeEntity> list = new ArrayList<>();
        for (DepEntity depEntity : depList) {
            TreeNodeEntity treeNodeEntity = new TreeNodeEntity(depEntity.getDepSerial().toString(), depEntity.getDepName(),
                    depEntity.getLeaf() == 0);
            list.add(treeNodeEntity);
        }
        return succMsgData(list);
    }

    /**
     * 获取部门序号
     * @return
     */
    @Logs
    @ApiOperation(value = "获取部门序号", notes = "获取部门序号")
    @RequestMapping(value = "/selectModuleDep", method = RequestMethod.GET)
    public JsonResult<Object> selectModuleDep() {
        //获取部门编号
        WtModuleEntity moduleEntity = wtModuleService.selectModuleDepByPrimaryKey(DEP_MODULE_ID);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("moduleDep",moduleEntity.getModuleDep());
        return succMsgData(jsonObject);
    }

    /**
     * 新增部门
     * @param entity
     * @return
     */
    @Logs
    @ApiOperation(value = "新增Dep信息", notes = "新增Dep信息")
    @RequestMapping(value = "/insertDep", method = RequestMethod.POST)
    public JsonResult<Object> insertDep(@RequestBody @Valid DepEntity entity) {

        //获取部门编号
        WtModuleEntity moduleEntity = wtModuleService.selectModuleDepByPrimaryKey(DEP_MODULE_ID);

        if(entity.getDepParent() == null || entity.getDepParent() == 0){
            return failMsg("选择要新增的上级部门");
        }
        //判断此级部门数 超过1296
        int count = depService.countDepByParent(entity.getDepParent());
        if(count >= 1296){
            return failMsg("此级目录数超过最大上限");
        }

        DepEntity parentEntity = depService.selectByPrimaryKey(entity.getDepParent().longValue());
        if(parentEntity == null){
            return failMsg("上级目录不存在");
        }
        String parentDepNo = parentEntity.getDepNo();
        if(parentDepNo.length() >= 41){
            return failMsg("部门最多有20个层级");
        }
        entity.setDepSerial(moduleEntity.getModuleDep().longValue());
        if(entity.getDepOrder() == null || entity.getDepOrder() >= count){
            entity.setDepOrder(count);
        }
        //插入在中间
        if(entity.getDepOrder().intValue() != count){
            //后边的部门更新
            List<DepEntity> list2 = depService.selectListMorethanOrder(entity.getDepParent(), entity.getDepOrder());
            depService.depReOrder(list2,entity.getDepSerial(),1);
        }
        String d = CharacterUtil.DeciamlToThirtySix(entity.getDepOrder().intValue());
        if(d.length() == 1){
            d = "0" + d;
        }
        entity.setDepNo(parentDepNo + d);
        depService.insertSelective(entity);

        //插入日志
        UserLogEntity record = new UserLogEntity();
        record.setLx(0);
        record.setLogType(1);
        record.setModuleId("0002");
        record.setLogBz(entity.getDepSerial()+"");
        record.setLogSj(new Date());
        String glyNo = null;
        JSONObject jsonObject = JwtUtils.getJwtData(request);
        if (jsonObject != null) {
            glyNo = jsonObject.getString("userSerial");
        }
        record.setLogIp(request.getRemoteAddr());
        record.setGlyNo(glyNo);
        userLogService.insertSelective(record);
        return succMsg();
    }


    /**
     * 删除部门条件判断
     * @param depSerial
     * @return
     */
    @Logs
    @ApiOperation(value = "删除Dep条件判断", notes = "删除Dep条件判断")
    @RequestMapping(value = "/deleteDepJudge", method = RequestMethod.GET)
    public JsonResult<Object> deleteDepJudge(@RequestParam Long depSerial) {

        if(depSerial == null || depSerial == 10000){
            return failMsg("根部门不能删除");
        }
        int depNo = depSerial.intValue();
        int childDep = depService.countDepByParent(depNo);
        if(childDep != 0){
            return failMsg("该部门包含子部门无法删除,请先删除该部门的子部门");
        }
        String msg = "具备删除条件";
        int childDepCount = depService.countDepByParent(depNo);
        if(childDepCount == 0){
            int curDepUserCount = userBaseService.countDepUser(depNo);
            if(curDepUserCount > 0 ){
                msg = "部门内存在员工，删除系统将自动把部门员工移动到总部门下";
            }
        }
        return succMsg(msg);
    }

    /**
     * 删除部门
     * @param depSerial
     * @return
     */
    @Logs
    @ApiOperation(value = "删除部门", notes = "删除部门")
    @RequestMapping(value = "/deleteDep", method = RequestMethod.GET)
    public JsonResult<Object> deleteDep(@RequestParam Long depSerial) {

        if(depSerial == null || depSerial == 10000){
            return failMsg("根部门不能删除");
        }
        int childDep = depService.countDepByParent(depSerial.intValue());
        if(childDep != 0){
            return failMsg("该部门包含子部门无法删除,请先删除该部门的子部门");
        }

        List<UserBaseEntity> list = userBaseService.selectUserListByDepNo(depSerial.intValue());

        //更新部门用户到根目录
        if(list != null && list.size() > 0){
            userBaseService.updateDepInfoByPrimaryKey(list);
        }
        DepEntity entity = depService.selectByPrimaryKey(depSerial);

        //同级相关部门重新排序
        List<DepEntity> list1 = depService.selectListMorethanOrder(entity.getDepParent(),entity.getDepOrder());
        depService.depReOrder(list1,depSerial,-1);

        //插入要删除的数据
        DepDeleteEntity deleteEntity = new DepDeleteEntity();
        deleteEntity.setDepSerial(depSerial);
        deleteEntity.setDepParent(entity.getDepParent());
        deleteEntity.setDepOrder(entity.getDepOrder());
        deleteEntity.setDepName(entity.getDepName());
        deleteEntity.setDepNo(entity.getDepNo());
        deleteEntity.setDepRule(entity.getDepRule());
        deleteEntity.setDepRegserial(entity.getDepRegserial());
        deleteEntity.setDepType(2);
        depDeleteService.insertSelective(deleteEntity);

        depService.deleteByPrimaryKey(depSerial);


        return succMsgData("操作成功!");
    }

    /**
     * 修改部门
     * @param entity
     * @return
     */
    @Logs
    @ApiOperation(value = "修改部门", notes = "修改部门")
    @RequestMapping(value = "/updateDep", method = RequestMethod.POST)
    public JsonResult<Object> updateDep(@RequestBody  DepEntity entity) {
        JSONObject jsonObject = new JSONObject();

        if(entity == null || entity.getDepSerial() == 10000){
            return failMsg("根部门不能修改");
        }
        DepEntity depEntity = depService.selectByPrimaryKey(entity.getDepSerial());


        if(!entity.getDepParent().equals(depEntity.getDepParent())){
            //新目录同级部门 重排序
            int childDepCount = depService.countDepByParent(entity.getDepParent());
            if(entity.getDepOrder() == null || childDepCount == 0 ){
                entity.setDepOrder(childDepCount);
            }else if(entity.getDepOrder() > childDepCount){
                entity.setDepOrder(childDepCount-1);
            }
            //插入在中间或前边
            if(entity.getDepOrder().intValue() != childDepCount){
                List<DepEntity> list2 = depService.selectListMorethanOrder(entity.getDepParent(), entity.getDepOrder());
                depService.depReOrder(list2,entity.getDepSerial(),1);
            }
            //原同级目录 重排序
            List<DepEntity> list1 = depService.selectListMorethanOrder(depEntity.getDepParent(),depEntity.getDepOrder());
            depService.depReOrder(list1,depEntity.getDepSerial(),-1);

            String d = CharacterUtil.DeciamlToThirtySix(entity.getDepOrder());
            if(d.length() == 1){
                d = "0" + d;
            }
            DepEntity destEntity = depService.selectByPrimaryKey(entity.getDepParent().longValue());
            String  depNo = destEntity.getDepNo();
            String newDepNo = depNo + d;
            entity.setDepNo(newDepNo);

            //处理当前部门子部门的 depNo 变更
            depService.childDepUserUpdate(entity.getDepSerial(),newDepNo,0);

        }else if(!entity.getDepOrder().equals(depEntity.getDepOrder())){
            //新目录同级部门 重排序
            int childDepCount = depService.countDepByParent(depEntity.getDepParent());

            if(entity.getDepOrder() >= childDepCount){
                entity.setDepOrder(childDepCount-1);
            }
            if(childDepCount == 0){
                entity.setDepOrder(0);
            }
            int up ;
            List<DepEntity> list2 ;
            int from ;
            int end ;
            if(entity.getDepOrder() < depEntity.getDepOrder()){
                from = entity.getDepOrder();
                end = depEntity.getDepOrder();
                up = 1;
            }else{
                from = depEntity.getDepOrder();
                end = entity.getDepOrder();
                up = -1;
            }
            list2 = depService.selectListBetwweenOrder(entity.getDepParent(),from,end);

            depService.depReOrder(list2,entity.getDepSerial(),up);

            String d = CharacterUtil.DeciamlToThirtySix(entity.getDepOrder());
            if(d.length() == 1){
                d = "0" + d;
            }
            String  depNo = depEntity.getDepNo();
            String newDepNo = depNo.substring(0,depNo.length() -2) + d;
            entity.setDepNo(newDepNo);
            //处理当前部门子部门的 depNo 变更
            depService.childDepUserUpdate(entity.getDepSerial(),newDepNo,0);
        }

        depService.updateByPrimaryKeySelective(entity);

        return succMsg("操作成功");
    }




}